package com.wdc.deliveryrobot.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.JsonReader;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.TableLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirui.selfstudysdk.mode.ChargingPosition;
import com.sirui.selfstudysdk.mode.MapData;
import com.wdc.deliveryrobot.R;

import java.nio.file.LinkOption;


public class MapView extends View{

    private MapData mapData;

    private ChargingPosition chargingPosition;

    private JSONArray jsonArrayPoint;
    private float scaleFactor = 1.0f; // 当前缩放比例
    private float focusX; // 缩放中心 X 坐标
    private float focusY; // 缩放中心 Y 坐标

    private float offsetX = 0; // X 轴偏移
    private float offsetY = 0; // Y 轴偏移
    private float lastTouchX; // 上一个触摸点 X
    private float lastTouchY; // 上一个触摸点 Y

    private int widthMap,heightMap;

    private JSONObject jsonObjectScan;

    private static String TAG = "mapView";

    private ScaleGestureDetector scaleGestureDetector;

    public MapView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());
    }

    public void setLaserData(MapData mapData,ChargingPosition chargingPosition,JSONArray jsonArray,JSONObject jsonObjectScan,int width,int height) {
        this.jsonObjectScan = jsonObjectScan;
        this.jsonArrayPoint = jsonArray;
        this.chargingPosition = chargingPosition;
        this.mapData = mapData;
        this.widthMap = width;
        this.heightMap = height;
        invalidate();  //绘制 调用draw
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        super.draw(canvas);

        // 将画布缩放到指定比例
        canvas.scale(scaleFactor, scaleFactor, focusX, focusY);
        canvas.translate(offsetX, offsetY);
//        float offsetX = (widthMap - mapData.getWidth() * scaleFactor) / 2;
//        float offsetY = (heightMap - mapData.getHeight() * scaleFactor) / 2;
//        // 将画布缩放到指定比例
//        canvas.scale(scaleFactor, scaleFactor, focusX, focusY);
//        canvas.translate(offsetX / scaleFactor, offsetY / scaleFactor);

        //绘制地图(已经生成玩意)
        canvas.save();
        canvas.translate(0,mapData.getHeight());
        canvas.scale(1,-1);
        canvas.drawBitmap(decodeBase64ToBitmap(this.mapData.getData()),null,new Rect(0,0,mapData.getWidth(),mapData.getHeight()),null);

        canvas.restore();


        canvas.translate(0,mapData.getHeight());
//        canvas.rotate((float) (180 * (Math.PI / 180)));
        canvas.scale(1,-1);
        Log.d(TAG,"接收到信息:" + chargingPosition.getX() + " " + chargingPosition.getY());

        //绘制点位先吧
        canvas.save();
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);

        if (jsonArrayPoint != null){
            //获取点位
            for (int i = 0;i < jsonArrayPoint.size();i ++){
//            Log.d(TAG,"点位信息: x-" + jsonArrayPoint.getJSONObject(i).getString("x") + "y-" + jsonArrayPoint.getJSONObject(i).getString("y")+ "yaw-" + jsonArrayPoint.getJSONObject(i).getString("yaw"));
                double x = Double.valueOf(jsonArrayPoint.getJSONObject(i).getString("x"));
                double y = Double.valueOf(jsonArrayPoint.getJSONObject(i).getString("y"));

                x = switchX(x);
                y = switchY(y);
//            Log.d(TAG,"转换的点位信息: x " + x + " y " + y);
                float xF = (float) x;
                float yF = (float) y;
                canvas.save();
                canvas.translate(-xF,-yF);
                canvas.drawCircle(0,0,3,paint);
                canvas.restore();
            }
        }


        //再画个充电桩
        canvas.save();
        float xCharging = chargingPosition.getX();
        float yCharging = chargingPosition.getY();

        xCharging =  switchX( xCharging);
        yCharging =  switchY(yCharging);
        Log.d(TAG,"充电桩信息：x " + xCharging + " y " + yCharging);
        canvas.translate(-xCharging,-yCharging);
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.mapcharging),null,new Rect(5,5,-5,-5),null);
        canvas.restore();

        //画个机器人
        canvas.save();
        //获取机器的坐标
        double xRD = jsonObjectScan.getJSONObject("laserpos").getDouble("x");
        double yRD= jsonObjectScan.getJSONObject("laserpos").getDouble("y");
        xRD = switchX(xRD);
        yRD = switchY(yRD);
        float xR = (float) xRD;
        float yR = (float) yRD;
        canvas.translate(-xR,-yR);
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.robot),null,new Rect(5,5,-5,-5),null);

        canvas.restore();


        canvas.restore();
    }

    private Bitmap decodeBase64ToBitmap(String base64String) {

        String base64Image = base64String.split(",")[1];

        // 解码 Base64 字符串
        byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);

        // 将字节数组转换为 Bitmap
        return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        scaleGestureDetector.onTouchEvent(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastTouchX = event.getX();
                lastTouchY = event.getY();
                break;

            case MotionEvent.ACTION_MOVE:
                float dx = event.getX() - lastTouchX;
                float dy = event.getY() - lastTouchY;
                offsetX += dx; // 更新 X 轴偏移
                offsetY += dy; // 更新 Y 轴偏移
                lastTouchX = event.getX();
                lastTouchY = event.getY();
                invalidate(); // 重新绘制
                break;
        }
        return true; // 返回 true，表示事件已处理
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            scaleFactor *= detector.getScaleFactor(); // 更新缩放比例
            scaleFactor = Math.max(0.5f, Math.min(scaleFactor, 3.0f)); // 限制缩放范围
            focusX = detector.getFocusX(); // 获取缩放中心 X
            focusY = detector.getFocusY(); // 获取缩放中心 Y
            invalidate(); // 重新绘制
            return true;
        }
    }

    private double switchX(double x){
        //世界坐标转为像素坐标
        x = (x - mapData.getOffx()) / mapData.getResolution();
        x = x- x * 2;
        return x;
    }

    private double switchY(double y){
        //世界坐标转为像素坐标
        y = (y - mapData.getOffy()) / mapData.getResolution();
        y = y- y * 2;
        return y;
    }

    private float switchX(float x){

        x = (float) ((x - mapData.getOffx()) / mapData.getResolution());
        x = x- x * 2;
        return x;
    }

    private float switchY(float y){

        y = (float) ((y - mapData.getOffy()) / mapData.getResolution());
        y = y- y * 2;
        return y;
    }
}
